//ts内置工具

//1. Partial<T> - 将所有属性变为可选
interface User {
  id: number;
  name: string;
  age: number;
}

type PartialUser = Partial<User>;
// 等价于 { id?: number; name?: string; age?: number; }

const updateUser: PartialUser = { name: "John" }; // 只更新部分属性


//2. Required<T> - 将所有属性变为必填
interface Config {
  url?: string;
  timeout?: number;
}

type RequiredConfig = Required<Config>;
// 等价于 { url: string; timeout: number; }

//3. Readonly<T> - 将所有属性变为只读
interface State {
  count: number;
}

type ReadonlyState = Readonly<State>;
const state: ReadonlyState = { count: 0 };
// state.count = 1; // 错误：无法分配到 "count"，因为它是只读属性

//4. Pick<T, K> - 从类型中选择指定属性
interface Product {
  id: number;
  name: string;
  price: number;
  description: string;
}

type ProductPreview = Pick<Product, 'id' | 'name'>;
// 等价于 { id: number; name: string; }

//5. Omit<T, K> - 从类型中排除指定属性
type ProductWithoutPrice = Omit<Product, 'price'>;
// 等价于 { id: number; name: string; description: string; }

//6. Record<K, T> - 创建键值对类型
type UserRoles = Record<string, boolean>;
// 等价于 { [key: string]: boolean }

const roles: UserRoles = {
  admin: true,
  user: false
};

type SpecificRecord = Record<'name' | 'email', string>;
// 等价于 { name: string; email: string }

//7. Exclude<T, U> - 从联合类型中排除某些类型
type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
type T1 = Exclude<string | number | (() => void), Function>; // string | number

//8. Extract<T, U> - 从联合类型中提取某些类型
type T2 = Extract<"a" | "b" | "c", "a" | "f">; // "a"
type T3 = Extract<string | number | (() => void), Function>; // () => void

//9. NonNullable<T> - 排除 null 和 undefined
type T4 = NonNullable<string | number | undefined>; // string | number
type T5 = NonNullable<string[] | null | undefined>; // string[]

//10. ReturnType<T> - 获取函数返回类型
function getUser() {
  return { name: "John", age: 30 };
}

type UserReturnType = ReturnType<typeof getUser>;
// 等价于 { name: string; age: number }

//11. Parameters<T> - 获取函数参数类型
function createUser(name: string, age: number) {
  return { name, age };
}

type UserParams = Parameters<typeof createUser>;
// 等价于 [name: string, age: number]

//12. Awaited<T> - 获取 Promise 的解析类型
async function fetchData() {
  return { data: "some data" };
}

type FetchDataResult = Awaited<ReturnType<typeof fetchData>>;
// 等价于 { data: string }